'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')

function resolve(dir) {
  return path.join(__dirname, dir)
}

/*
* 运行npm run dev进行开发调试的时候,此时会加载执行 .env.development 文件内容
* 运行npm run build:prod进行生产环境打包的时候,会加载执行 .env.production 文件内容
* */
const name = defaultSettings.title || 'vue Element Admin' // 网页标题
const port = process.env.port || process.env.npm_config_port || 9527 // 端口

const CopyWebpackPlugin = require('copy-webpack-plugin')

// vue.config.js 配置说明
// 官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions
module.exports = {
  publicPath: defaultSettings.context,   // 部署应用包时的基本 URL,此处context: '/web'
  outputDir: 'dist',    // 在npm run build 时 ,生成文件的目录名称（要和baseUrl的生产环境路径一致）（默认dist）
  assetsDir: 'static',  // 用于放置生成的静态资源 (js、css、img、fonts) 的；（项目打包之后，静态资源会放在这个文件夹下）
  // 开发时进行语法验证，如果不想要可以改成lintOnSave: false
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,  // 如果不需要生产环境的 source map，可以将其设置为 false 以加速生产环境构建。
  // webpack-dev-server 相关配置
  devServer: {
    port: port,
    open: false,
    disableHostCheck: true,
    overlay: {
      warnings: false,
      errors: true
    },
    // 代理配置:如果前端应用和后端 API 服务器没有运行在同一个主机上，需要在开发环境下将 API 请求代理到 API 服务器。
    proxy: {
      // 代理1
      [process.env.VUE_APP_BASE_API]: {
        //target: 'http://192.168.1.118:8080', // 跨域请求的地址
        target: 'http://localhost:9080',
        changeOrigin: true     // true时，表示开启跨域
      },
      // 代理2
      '/web/auth/create-debug': {
        target: 'http://localhost:9080',
        changeOrigin: true
      },
      //  代理3
      '/webpc': {
        target: 'http://localhost:9080',
        changeOrigin: true
      }
    }
  },
  configureWebpack: {
    name: name,
    resolve: {
      alias: {
        '@': resolve('src'),
        '@utils': resolve('src/utils'),
        '@components': resolve('src/components'),
        '@api': resolve('src/api')
      }
    },
    plugins: [
      new CopyWebpackPlugin([{
        from: './static',
        to: 'static'
      }])
    ]
  },
  chainWebpack(config) {
    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        // to ignore runtime.js
        // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ])

    config.plugins.delete('prefetch')

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
            // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
          config.optimization.runtimeChunk('single')
        }
      )
  }
}
